/*
 * Copyright (c) 2012-2013, Yunnan Yuan Xin technology Co., Ltd.
 * 
 * All rights reserved.
 */
package net.jeeshop.web.action.phone;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yuanxin.framework.service.ServiceResult;
import com.yuanxin.framework.util.DateTimeUtils;
import com.yuanxin.service.biz.schcenter.appobject.OrderAO;
import com.yuanxin.service.biz.schcenter.entity.gen.OrderCriteria;
import com.yuanxin.service.biz.schcenter.service.IOrderService;
import com.yuanxin.service.biz.schuserbase.appobject.OrganMemberEntityAO;
import com.yuanxin.service.biz.schuserbase.appobject.StudentMemberAO;
import com.yuanxin.service.biz.schuserbase.entity.gen.StudentMemberCriteria;
import com.yuanxin.service.biz.schuserbase.service.IStudentMemberService;
import com.yuanxin.service.biz.schuserbase.util.SchUserUtil;

import net.jeeshop.app.appobject.FileInfoAO;
import net.jeeshop.app.appobject.PaymentAO;
import net.jeeshop.app.appobject.ReturnProductInfoAO;
import net.jeeshop.app.dao.gen.FileInfoGeneratedMapper;
import net.jeeshop.app.entity.gen.FileInfoCriteria;
import net.jeeshop.core.FrontContainer;
import net.jeeshop.core.Services;
import net.jeeshop.core.kuaidi100Helper;
import net.jeeshop.core.dao.page.PagerModel;
import net.jeeshop.core.front.SystemManager;
import net.jeeshop.core.util.DateTimeUtil;
import net.jeeshop.core.util.HttpUtil;
import net.jeeshop.services.front.account.AccountService;
import net.jeeshop.services.front.account.bean.Account;
import net.jeeshop.services.front.address.AddressService;
import net.jeeshop.services.front.address.bean.Address;
import net.jeeshop.services.front.area.bean.Area;
import net.jeeshop.services.front.comment.CommentService;
import net.jeeshop.services.front.comment.bean.Comment;
import net.jeeshop.services.front.express.bean.Express;
import net.jeeshop.services.front.order.OrderService;
import net.jeeshop.services.front.order.bean.Order;
import net.jeeshop.services.front.order.bean.OrderSimpleReport;
import net.jeeshop.services.front.orderdetail.OrderdetailService;
import net.jeeshop.services.front.orderdetail.bean.Orderdetail;
import net.jeeshop.services.front.orderpay.OrderpayService;
import net.jeeshop.services.front.orderpay.bean.Orderpay;
import net.jeeshop.services.front.ordership.OrdershipService;
import net.jeeshop.services.front.ordership.bean.Ordership;
import net.jeeshop.services.front.product.ProductService;
import net.jeeshop.services.front.product.bean.Product;
import net.jeeshop.services.front.product.bean.ProductStockInfo;
import net.jeeshop.services.manage.keyvalue.KeyvalueService;
import net.jeeshop.services.manage.keyvalue.bean.Keyvalue;
import net.jeeshop.web.action.front.FrontBaseController;
import net.jeeshop.web.action.front.orders.CartInfo;
import net.jeeshop.web.util.RequestHolder;
import net.jeeshop.web.util.SingleLoginUtil;

/**
 * Hello控制器。
 * 
 */
@Controller
@RequestMapping(value = "/phone/order")
public class OrderController extends FrontBaseController<Order> {

	private static final org.slf4j.Logger LOG =  LoggerFactory.getLogger(OrderController.class);
	@Resource
	private SingleLoginUtil singleLoginUtil;
	@Autowired
	private OrderService orderService;
	@Autowired
	private OrderdetailService orderdetailService;
	@Autowired
	private OrderpayService orderpayService;
	@Autowired
	private ProductService productService;
	@Autowired
	private CommentService commentService;
	@Autowired
	private OrdershipService ordershipService;
	@Autowired
	private AddressService addressService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private KeyvalueService keyvalueService;
	@Resource
	private FileInfoGeneratedMapper fileInfoGeneratedMapper;
	@Resource
	private IOrderService schOrderService;
	@Resource
	private IStudentMemberService studentMemberService;
	
	DecimalFormat df = new DecimalFormat("0.00");
	
	//获取流水号 center 应用地址 部署生产需要修改此地址
	//static final String CENTER_URL = "http://127.0.0.1:8881/center/phone/pay";
	/**
	 * App应用里面 -- 设置 --我的订单
	 * @param model
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws Exception
	 */
    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/index", method = { RequestMethod.GET, RequestMethod.POST })
    public String index(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception{
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setContentType("text/html;charset=utf-8"); 
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        //将当前运用名称传到前端
        model.addAttribute("appId", "seller");
        model.addAttribute("title", "我的订单");
        String pageNo = request.getParameter("pageNo");
        String pageSize = request.getParameter("pageSize");
        int no = 1;
        int size = 20;
        if(StringUtils.isNotBlank(pageNo)) {
        	no = Integer.parseInt(pageNo);
        }
        if(StringUtils.isNotBlank(pageSize)) {
        	size = Integer.parseInt(pageSize);
        }
        //获取我的订单信息
        //待付款订单
        PagerModel pager = new PagerModel();
        /*//未付款已取消订单
        PagerModel pager1 = new PagerModel();
        //已付款订单 取消订单
        PagerModel pager2 = new PagerModel();
        
        //已付款订单 
        PagerModel pager3 = new PagerModel(); 
        
        //已发货订单 取消订单
        PagerModel pager4 = new PagerModel();
        
      //其他订单 取消订单
        PagerModel pager5 = new PagerModel();*/
        
        OrderSimpleReport orderSimpleReport = new OrderSimpleReport();
        String userId = "";
        //获取订单信息之前先执行单点登录
        Account acc = new Account();
        String token = request.getParameter("token");
        OrganMemberEntityAO om = null;
        if(StringUtils.isNotBlank(token)){
    		om = SchUserUtil.getOrganMemberEntityAO(token);
    		if(om != null){
    			String baseUserId = om.getId();
            	Account e = new Account();
            	e.setBaseuserid(baseUserId);
            	acc = accountService.selectOne(e);
    		}
    	}
        acc = singleLoginUtil.singleLogin(token);
        if(acc != null && StringUtils.isNotBlank(acc.getId())){
        	userId = acc.getAccount();
        	 pager = getMyOrders(acc.getAccount());
    		//查询汇总
    		 orderSimpleReport = orderService.selectOrdersSimpleReport(acc.getAccount());
    		LOG.info("orderSimpleReport="+orderSimpleReport);
        	
        }
        model.addAttribute("pager", pager);
        model.addAttribute("userId", userId);
        model.addAttribute("orderSimpleReport", orderSimpleReport);
        model.addAttribute("token", token);
        List<OrderAO> nbList = new ArrayList<OrderAO>();
        List<OrderAO> xyczList = new ArrayList<OrderAO>();
        List<OrderAO> shList = new ArrayList<OrderAO>();
        List<PaymentAO> payList = new ArrayList<PaymentAO>();
        if(null != om) {
        	String mobile = om.getMobile();
        	List<String> code = new ArrayList<String>();
        	code.add(om.getCode());
        	if(StringUtils.isNotBlank(mobile)) {
        		StudentMemberCriteria smc = new StudentMemberCriteria();
    			smc.or().andMotherMobileEqualTo(mobile);
    			smc.or().andFatherMobileEqualTo(mobile);
    			smc.or().andThreeMobileEqualTo(mobile);
    			smc.or().andFourMobileEqualTo(mobile);
    			smc.or().andFiveMobileEqualTo(mobile);
            	ServiceResult<List<StudentMemberAO>> sRet = studentMemberService.selectByCriteria(smc);
            	if (sRet.isSucceed() && sRet.getData() != null && !sRet.getData().isEmpty()) {
            		for (StudentMemberAO ao : sRet.getData()) {
            			code.add(ao.getMemberCode());
            		}
            	}
        	}
        	List<OrderAO> list = schOrderService.selectList(code);
        	for(OrderAO ao : list) {
        		if("0".equals(ao.getType())) {
        			xyczList.add(ao);//充值;
        		} else if("7".equals(ao.getType())) {
        			nbList.add(ao);//校园
        		} else {
        			shList.add(ao);//生活缴费
        		}
        	}
        	StringBuffer requrl = request.getRequestURL();
            String tempContextUrl = requrl.delete(requrl.length()-request.getRequestURI().length(), requrl.length()).append("/").toString();
            tempContextUrl += "school/phone/payment/orderList?token="+token+"&pageNo="+no+"&pageSize="+size+"&memberCode="+om.getCode();
            String responseHttp = HttpUtil.get(tempContextUrl,"post","UTF-8");
    		Map<String,Object> map = (Map<String, Object>) JSON.parse(responseHttp);
    		//JSONArray data = JSONArray.fromObject(map.get("data"));
    		JSONArray data = JSONArray.parseArray( JSON.toJSONString(map.get("data")));
    		
    		
    		if (null != data && data.size() > 0 && !"[null]".equals(data.toString()) && !"".equals(data.toString())) {
    			for (int i = 0; i < data.size(); i++) {
        			JSON jobj = data.getJSONObject(i);
        			PaymentAO ao = (PaymentAO) JSON.toJavaObject(jobj,PaymentAO.class);
        			payList.add(ao);
        		}
    		}
        }
        model.addAttribute("xyjfList", payList);
        model.addAttribute("nbList", nbList);
        model.addAttribute("xyczList", xyczList);
        model.addAttribute("shList", shList);
        return "phone/order/index";
    }
    
    
    //购物车- 生成订单-->确认支付
    @RequestMapping(value = "/confirm", method = { RequestMethod.GET, RequestMethod.POST })
    public String confirm(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	String id = request.getParameter("orderId");
    	String token = request.getParameter("token");
    	Order e = new Order();
    	
    	e = getOrderInfo(id,e,model,request);
        //将当前运用名称传到前端
        model.addAttribute("appId", "seller");
        model.addAttribute("title", "商城订单确认");
        model.addAttribute("e", e);
        model.addAttribute("token", token);
        return "phone/order/confirm";
    }
    
    @RequestMapping(value = "/result", method = { RequestMethod.GET, RequestMethod.POST })
    public String result(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	String id = request.getParameter("orderId");
    	String orderShipID = request.getParameter("orderShipId");
    	String addressID = request.getParameter("addressId");
    	String token = request.getParameter("token");
    	Order e = new Order();
    	Product p = new Product();
    	
    	if(e!= null && StringUtils.isNotBlank(e.getProductID()+"")){
    		p.setId(e.getProductID()+"");
    		p = productService.selectOne(p);
    	}
    	if(p != null){
    		productService.updateStockAfterPaySuccess(p);
    	}
    	e = getOrderInfo(id,e,model,request);
    	
    	//支付成功，更新各种状态，以及修改订单地址
    	Address add = new Address();
    	String orderShipAddress = "";
    	if(StringUtils.isNotBlank(addressID)){
    		add.setId(addressID);
    		add.setIsdefault("y");
    		add = addressService.selectOne(add);
    		orderShipAddress = add.getAddress();
    	}
    	if(StringUtils.isNotBlank(orderShipID)){
    		Ordership ordership = new Ordership();
    		ordership.setId(orderShipID);
    		ordership.setOrderid(id);
    		if(StringUtils.isNotBlank(orderShipAddress)){
    			ordership.setShipaddress(orderShipAddress);
    		}
    		ordershipService.update(ordership);
    	}
    	if(e != null && StringUtils.isNotBlank(e.getId())){
    		e.setPaystatus("y");
    		e.setStatus("pass");
    		orderService.update(e);
    	}
    	 model.addAttribute("e", e);
        //将当前运用名称传到前端
        model.addAttribute("appId", "seller");
        model.addAttribute("title", "商城订单支付结果");
        model.addAttribute("token", "token");
        return "phone/order/result";
    }
    
    @RequestMapping(value = "/detail", method = { RequestMethod.GET, RequestMethod.POST })
    public String detail(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){

    	String id = request.getParameter("orderId");
    	Order e = new Order();
    	int hit = 0;
    	e = getOrderInfo(id,e,model,request);
    	if(e != null && StringUtils.isNotBlank(e.getProductID()+"")){
    		Product p =new Product();
    		p.setId(e.getProductID()+"");
    		p = productService.selectOne(p);
    		if(p != null){
    			productService.updateHit(p);
    		}
    	}
    	model.addAttribute("e", e);
        //将当前运用名称传到前端
        model.addAttribute("appId", "seller");
        model.addAttribute("title", "商城订单详情");
        return "phone/order/detail";
    }
    @RequestMapping(value = "/update", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
	public Object cancleOrderStatus(HttpServletRequest request){
    	String result = "false";
    	String orderId = request.getParameter("orderId");
    	String userId = request.getParameter("userId");
    	String status = request.getParameter("status");
    	int updateFlag = 0;
    	if(StringUtils.isNotBlank(orderId) && StringUtils.isNotBlank(userId)){
    		Order order = new Order();
    		order.setId(orderId);
    		order.setAccount(userId);
    		order = orderService.selectOne(order);
    		if(order != null){
    			order.setStatus(status);
    			updateFlag = orderService.update(order);
    		}
    		if(updateFlag != 0){
    			result = "true";
    		}
    	}
    	return  result;
    }
    
    @RequestMapping(value = "/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
	public Object deleteOrder(HttpServletRequest request){
    	String result = "false";
    	String orderId = request.getParameter("orderId");
    	String userId = request.getParameter("userId");
    	int updateFlag = 0;
    	if(StringUtils.isNotBlank(orderId) && StringUtils.isNotBlank(userId)){
    		Order order = new Order();
    		order.setId(orderId);
    		order.setAccount(userId);
    		updateFlag = orderService.delete(order);
    		if(updateFlag != 0){
    			result = "true";
    		}
    	}
    	return  result;
    }
    
    /**
    * 分页获取我的订单列表，首页分页查询订单集合，然后把查询到的ID集合仍到一个多表联合的查询里面，查询出更多的信息。分页显示用户的订单只用一个SQL貌似不好搞的。想到好办法再去优化。
	 * @throws Exception
	 * @param account 用户登录ID
	 */
	private PagerModel getMyOrders(String account) throws Exception {
		//分页查询订单ID集合
//		super.selectList();
		//1、分页查询订单集合
		PagerModel pager = selectMyOrders(account);
		//根据上面查询出来的ID集合，多表联合查询出订单和订单明细数据
		List<Order> ordersTemp = pager.getList();
		List<String> ids = new LinkedList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(int i=0;i<ordersTemp.size();i++){
			Order orderItem = ordersTemp.get(i);
			//时间转换成可以阅读的格式
			orderItem.setCreatedate(DateTimeUtil.getDateTimeString(sdf.parse(orderItem.getCreatedate())));//转换为几小时前，几天前等形式
			//orderItem.setCreatedate(DateTimeUtils.formateDateToStr(DateTimeUtils.parseStrToDate(orderItem.getCreatedate(), DateTimeUtils.FORMAT_YMD_HMS), DateTimeUtils.FORMAT_YMD_HMS));//转换为年月日时分秒形式
			ids.add(orderItem.getId());
		}
		
		Order order = new Order();
		order.clear();
		order.setAccount(account);
		order.setQueryOrderIDs(ids);
		//2、查询指定订单集合的所有订单项集合，然后内存中对订单项进行分组
		List<Order> myOrders = orderService.selectList(order);
		if(myOrders!=null && myOrders.size()>0){
			for(int i=0;i<ordersTemp.size();i++){
				Order orderItem = ordersTemp.get(i);
				for(Iterator<Order> it = myOrders.iterator();it.hasNext();){
					Order orderdetail = it.next();
//					logger.error("orderdetail.getId()="+orderdetail.getId());
//					logger.error("orderItem.getId()="+orderItem.getId());
					if(orderdetail.getId().equals(orderItem.getId())){
						orderItem.getOrders().add(orderdetail);
						it.remove();
					}
				}
			}
		}
		
//		Map<String, Order> orderMap = new HashMap<String, Order>();
		//处理成页面显示的数据格式
//		if(myOrders!=null && myOrders.size()>0){
//			orderMap.clear();
//			for(int i=0;i<myOrders.size();i++){
//				order = myOrders.get(i);
//				Order entry = orderMap.get(order.getId());
//				if(entry==null){
//					//添加订单
//					orderMap.put(order.getId(), order);
//					//添加订单项
//					order.getOrders().add(order);
//					continue;
//				}
//				
//				//否则添加订单到此MAP订单的orders集合中，此集合存储的是订单明细信息
//				entry.getOrders().add(order);
//			}
//			myOrders.clear();
//			myOrders.addAll(orderMap.values());
//			orderMap.clear();
//
//			//根据订单ID排序
//			Collections.sort(myOrders, new Comparator<Order>() {
//				@Override
//				public int compare(Order o1, Order o2) {
//					int id1 = Integer.valueOf(o1.getId());
//					int id2 = Integer.valueOf(o2.getId());
//					if (id1 > id2) {
//						return 1;
//					} else if (id1 < id2) {
//						return 2;
//					}
//					return 0;
//				}
//			});
//			getPager().setList(myOrders);
//		}
//		getSession().setAttribute(FrontContainer.selectMenu, "user_centers");
		return pager;
	}
	
	/**
	 * 分页查询订单集合
	 * @return
	 * @throws Exception
	 */
	private PagerModel selectMyOrders(String account) throws Exception {
		int offset = 0;
		if (RequestHolder.getRequest().getParameter("pager.offset") != null) {
			offset = Integer
					.parseInt(RequestHolder.getRequest().getParameter("pager.offset"));
		}
		if (offset < 0)
			offset = 0;
		
		PagerModel pager = new PagerModel();
		Order order = new Order();
		order.setAccount(account);
		order.setOffset(offset);
		order.setPageSize(99999999);
		pager = orderService.selectPageList(order);
		
		if(pager==null)pager = new PagerModel();
		// 计算总页数
//		pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)
//				/ pager.getPageSize());
		
//		selectListAfter();
		//pager.setPagerUrl("orders");
		return pager;
	}
	
	/**
	 * 根据前台回传订单ID获取 订单详细信息
	 * */
	public Order getOrderInfo(String id,Order e,Model model,HttpServletRequest request){
		Account acc = new Account();
		Address address = new Address();
		Comment c = new Comment();
    	Orderdetail orderdetail = new Orderdetail();
    	String token = request.getParameter("token");
        acc = getLoginAccount();
        //获取当前登录信息
        OrganMemberEntityAO om = SchUserUtil.getOrganMemberEntityAO(token);
        /*//测试用
        om = new OrganMemberEntityAO();
        om.setName("张晓华");
        om.setId("12345");
        om.setMobile("13311779625");
        acc.setAccount("test1");*/
        if(null == acc) {
        	acc = singleLoginUtil.singleLogin(token);
        }
		model.addAttribute("account", acc);
		//确保用户登录，订单ID不为空才获取订单信息
    	if(StringUtils.isNotBlank(id) && acc != null && StringUtils.isNotBlank(acc.getAccount())){
            if(om != null){
            	 model.addAttribute("baseUserNAme", om.getName());
            	 model.addAttribute("baseUserId", om.getId());
            	 model.addAttribute("baseUserPh", om.getMobile());
            }
    		//查询订单信息
    		Order order = new Order();
    		order.setId(id);
    		order.setAccount(acc.getAccount());
    		List<Order> orders = orderService.selectOrderInfo(order);
    		if(orders==null || orders.size()==0){
    			throw new NullPointerException("根据订单ID查询不到订单信息！");
    		}
    		LOG.error("orders.size="+orders.size());
    		 e = orders.get(0);
    		e.setOrders(orders);
    		//查询订单配送信息
    		Ordership ordership = new Ordership();
    		ordership.setOrderid(id);
    		ordership = ordershipService.selectOne(ordership);
    		if(ordership==null){
    			throw new NullPointerException("根据订单ID查询不到订单配送信息！");
    		}
    		e.setOrdership(ordership);
    		
    		//查询订单物流信息
    		e.setKuaid100Info(kuaidi100Helper.selectKuaidi100());
    		
    		//获取用户默认收货地址
        	address.setAccount(acc.getAccount());
        	address.setIsdefault("y");
        	address=addressService.selectOne(address);
        	List<Address> list = addressService.selectList(address);
        	
        	//获取用户留言
        	if(StringUtils.isNotBlank(id)){
        		int orderid = Integer.valueOf(id);
        		orderdetail.setOrderID(orderid);
    			List<Orderdetail> list1 = orderdetailService.selectList(orderdetail);
    			if(list != null && !list.isEmpty() && list.size() >0){
    				orderdetail = list1.get(0);
    			}
    			c.setProductID(String.valueOf(orderdetail.getProductID()));
    			c.setOrderdetailID(orderdetail.getId());
    			c.setOrderID(String.valueOf(orderid));
    			c.setStatus("x");
    			c.setNickname("ly");
    			c.setStar(88);
    			c.setAccount(acc.getAccount());
    			c = commentService.selectOne(c);
        		
        	}
    	}
    	model.addAttribute("orderdetail", orderdetail);
    	model.addAttribute("address", address);
    	model.addAttribute("mjCmment", c);
    	return e;
	}
	
	
	/**
	 * 用户进行留言
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/mjLy", method = RequestMethod.POST)
	@ResponseBody
	public String doRate(Model model,HttpServletRequest request) throws Exception{
		String orderidStr = request.getParameter("orderid");
		String token = request.getParameter("token");
		String content = request.getParameter("lyContent");
		Account acc = singleLoginUtil.singleLogin(token);
		if(acc != null && StringUtils.isNotBlank(acc.getAccount()) && StringUtils.isNotBlank(orderidStr) && !StringUtils.isBlank(content)){
			int orderid = Integer.valueOf(orderidStr);
			Orderdetail orderdetail = new Orderdetail();
			orderdetail.setOrderID(orderid);
			List<Orderdetail> list = orderdetailService.selectList(orderdetail);
			if(list != null && !list.isEmpty() && list.size() >0){
				orderdetail = list.get(0);
			}
			//添加留言时先判断是否已经留过言，若已经留言先删除记录
			Comment c = new Comment();
			c.setProductID(String.valueOf(orderdetail.getProductID()));
			c.setOrderdetailID(orderdetail.getId());
			c.setOrderID(String.valueOf(orderid));
			c.setStatus("x");
			c.setNickname("ly");
			c.setStar(88);
			c.setAccount(acc.getAccount());
			
			c = commentService.selectOne(c);
			if(c != null && StringUtils.isNotBlank(c.getId())){
				commentService.delete(c);
			}
			c.setContent(content);
			
			commentService.insert(c);
			
		}
		
		return "true";
	}
	
	
	
	
	/**
	 * 
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addOrder", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object addOerder(Model model,HttpServletRequest request) throws Exception {
		
	Map jsonObject = new HashMap<>();
	//boolean checkFlag = checkLogin(request);
	Account account = getLoginAccount();
	//Account account = new Account();
	String id = request.getParameter("id");
	String[] proId = id.split(";");
	Double amount = 0.00;
	String token = request.getParameter("token");
	OrganMemberEntityAO  om = SchUserUtil.getOrganMemberEntityAO(token);
	if (null == om) {
		jsonObject.put("success", false);
		jsonObject.put("orderId", null);
		jsonObject.put("msg", "您未登录，请登录后重试！");
		logger.info("您未登录，请登录后重试！");
		return jsonObject;
	}
	if (account == null || StringUtils.isBlank(account.getAccount())) {
		account = singleLoginUtil.singleLogin(token);
	}
	
	//从session中获取用户购买的商品列表
	CartInfo cartInfo = getMyCart();
	if (cartInfo == null || cartInfo.getProductList().size() == 0) {
		//throw new NullPointerException("购物车中没有可支付的商品!");
		jsonObject.put("success", false);
		jsonObject.put("orderId", null);
		jsonObject.put("msg", "购物车中没有可支付的商品!");
		return jsonObject;
	}
	
	//检测商品是否都有库存,如果没有库存需要提醒用户
//	synchronized (SystemManager.product_stock_lock) {
		Map<String, ProductStockInfo> productStockMap = SystemManager.getInstance().getProductStockMap();
		boolean no = false;
		String productName = "";
		int buyCount = 0;
		for (int i = 0; i < cartInfo.getProductList().size(); i++) {
			Product product = cartInfo.getProductList().get(i);
			for(int j = 0; j < proId.length; j++) {
				if(proId[j].equals(product.getId())) {
					buyCount += product.getBuyCount();
					if(productStockMap.get(product.getId())==null){
						product.product_sorry_str = "抱歉，该商品目前库存不足！";
						productName = product.getName();
						no = true;
						continue;
					}
					ProductStockInfo stockInfo = productStockMap.get(product.getId());
					if(product.getBuyCount() > stockInfo.getStock()){
						//如果用户购买的某个商品的数量大于该商品的库存数，则提示
						product.product_sorry_str = "抱歉，该商品目前库存不足！";
						productName = product.getName();
						no = true;
					}
				}
			}
		}
		//库存不足，则刷最后支付页面，提示用户某些商品的库存不足，请重新选购
		if(no){
			jsonObject.put("success", false);
			jsonObject.put("orderId", null);
			jsonObject.put("msg", "《"+productName+"》商品库存不足！请重新选购");
			return jsonObject;
		}
		
//		if(!no){
//			//如果检查没有出现库存不足的情况，则进行砍库存操作
//			for (int i = 0; i < cartInfo.getProductList().size(); i++) {
//				Product product = cartInfo.getProductList().get(i);
//				ProductStockInfo stockInfo = SystemManager.productStockMap.get(product.getId());
//				stockInfo.setStock(stockInfo.getStock() - product.getBuyCount());
//				stockInfo.setChangeStock(true);
//				SystemManager.productStockMap.put(product.getId(),stockInfo);
//			}
//		}
//	}
	
	//获取配送方式
	Express express = SystemManager.getInstance().getExpressMap().get("EXPRESS");
	if(express==null){
		//throw new NullPointerException("没有编码为EXPRESS的配送方式！本次请求视为非法！");
		jsonObject.put("success", false);
		jsonObject.put("orderId", null);
		jsonObject.put("msg", "没有编码为EXPRESS的配送方式！本次请求视为非法！");
		return jsonObject;
	}
	
	//创建订单对象
	Order order = new Order();
	order.setAccount(account.getAccount());
	order.setQuantity(buyCount);
	order.setRebate(1);
	order.setStatus(Order.order_status_init);
	order.setPaystatus(Order.order_paystatus_n);
	//商品总金额
//	double ptotal = 0d;
	int score = 0;//订单积分 等于订单项中每个商品赠送的积分总和
	//创建订单明细集合
	List<Orderdetail> orderdetailList = new LinkedList<Orderdetail>();
	for (int i = 0; i < cartInfo.getProductList().size(); i++) {
		Product product = cartInfo.getProductList().get(i);
		for(int j = 0; j < proId.length; j++) {
			if(proId[j].equals(product.getId())) {
//				ProductStockInfo momeryProduct = SystemManager.productStockMap.get(product.getId());
//				if(StringUtils.isNotBlank(momeryProduct.getActivityID())){
//					Activity activity = SystemManager.activityMap.get(momeryProduct.getActivityID());
//					String discountType = activity.getDiscountType();
//					if(discountType.equals(Activity.activity_discountType_r)){
//						//
//						double finalPrice = Double.valueOf(product.getNowPrice()) - Double.valueOf(activity.getDiscount());
//						
//					}else if(discountType.equals(Activity.activity_discountType_d)){
//						
//					}
//				}
				amount += Double.valueOf(product.getNowPrice()) * product.getBuyCount();
				Orderdetail orderdetail = new Orderdetail();
				orderdetail.setProductID(Integer.valueOf(product.getId()));
				orderdetail.setGiftID(product.getGiftID());//商品赠品ID
				orderdetail.setPrice(product.getNowPrice());//商品现价
				orderdetail.setNumber(product.getBuyCount());//购买数
				orderdetail.setFee("0");//配送费
				orderdetail.setProductName(product.getName());
				orderdetail.setTotal0(String.valueOf(Double.valueOf(orderdetail.getPrice()) * orderdetail.getNumber()));//订单项小计
				orderdetail.setScore(product.getScore());//活的赠送的积分
				if(product.getBuySpecInfo()!=null){
					//按照规格计算
					orderdetail.setSpecInfo("尺寸:"+product.getBuySpecInfo().getSpecSize()+",颜色:"+product.getBuySpecInfo().getSpecColor());
//					ptotal+= Double.valueOf(product.getBuySpecInfo().getSpecPrice()) * product.getBuyCount();
//					score+= product.getScore();
				}else{
				}
//				ptotal+= Double.valueOf(product.getNowPrice()) * product.getBuyCount();
				score+= product.getScore();
				orderdetailList.add(orderdetail);
			}
		}
	}
	if(orderdetailList.size()==1){
		order.setRemark(orderdetailList.get(0).getProductName());
	}else{
		order.setRemark("合并|"+orderdetailList.size()+"笔订单");
	}
	cartInfo.totalCacl();
	order.setScore(score);
	order.setExpressCode(express.getCode());//配送方式编码
	order.setExpressName(express.getName());//配送方式名称
	order.setFee(String.valueOf(express.getFee()));//订单配送费
	order.setPtotal(cartInfo.getAmount());//订单商品总金额
	//order.setAmount(String.valueOf(Double.valueOf(cartInfo.getAmount())+Double.valueOf(order.getFee())));//订单总金额 = 内存订单总金额 + 总配送费
	order.setAmount(String.valueOf(amount+express.getFee()));
	order.setAmountExchangeScore(cartInfo.getTotalExchangeScore());//订单总兑换积分。订单支付成功以后扣除
	
	/**
	 * 对金额进行格式化，防止出现double型数字计算造成的益出。
	 */
	logger.info("order.getAmount()=" + order.getAmount());
	order.setAmount(df.format(Double.valueOf(order.getAmount())));//订单总金额
	order.setPtotal(df.format(Double.valueOf(order.getPtotal())));//订单商品总金额
	order.setFee(df.format(Double.valueOf(order.getFee())));//订单总配送费
	
	/**
	 * 配送地址信息
	 */
	Ordership ordership = new Ordership();
	ordership.setOrderid(order.getId());
	
	Address add = new Address();
	add.setAccount(account.getAccount());
	add.setIsdefault("y");
	add = addressService.selectOne(add);
	if(add==null){
		//throw new NullPointerException("根据account="+account.getAccount()+"查询不到默认配送地址信息！本次请求视为非法！");
		jsonObject.put("success", false);
		jsonObject.put("orderId", null);
		jsonObject.put("msg", "请设置默认收货地址后重试！");
		return jsonObject;
	}
	logger.info(add.toString());
	
//	Area area = SystemManager.getInstance().getAreaMap().get(add.getProvince());//获取省份对象
//	String proinceName = area.getName();//省份名称
//	String cityName = null;//城市名称
//	String areaName = null;//区名称
//	List<Area> citys = area.getChildren();
//	if(citys!=null && citys.size()>0){
//		for(int i=0;i<citys.size();i++){
//			Area cityItem = citys.get(i);
//			if(cityItem.getCode().equals(add.getCity())){
//				cityName = cityItem.getName();
//				//获取所在区域名称
//				if(StringUtils.isNotBlank(add.getArea())){
//					List<Area> areaList = cityItem.getChildren();
//					if(areaList!=null && areaList.size()>0){
//						for(int m=0;m<areaList.size();m++){
//								areaName = areaList.get(m).getName();
//						}
//					}
//				}
//			}
//		}
//	}
	ordership.setShipname(add.getName());
	//ordership.setShipaddress(proinceName+cityName+add.getAddress());
	ordership.setShipaddress(add.getAddress());
	//ordership.setProvinceCode(add.getProvince());
	ordership.setProvince(add.getProvince());
	//ordership.setCityCode(add.getCity());
	ordership.setCity(add.getCity());
	//ordership.setAreaCode(add.getArea());
	ordership.setArea(add.getArea());
	ordership.setPhone(add.getMobile());
	ordership.setTel(add.getMobile());
	ordership.setZip(add.getZip());
	ordership.setSex("1");
	logger.info(ordership.toString());
	
	//创建订单并插入到数据库
	boolean res = orderService.createOrder(order, orderdetailList,ordership);
	if(res) {
		jsonObject.put("success", true);
		jsonObject.put("orderId", order.getId());
		jsonObject.put("msg", "生成订单成功");
		//清空购物车
		for(Iterator<Product> it = cartInfo.getProductList().iterator();it.hasNext();){
			Product p = it.next();
			for (String did : proId){
				if(p.getId().equals(did)){
					it.remove();
					//重新计算总支付金额
//					cartInfo.setAmount(cartInfo.totalCacl());
					cartInfo.totalCacl();
					break;
				}
			}
		}
		RequestHolder.getSession().setAttribute(FrontContainer.myCart, cartInfo);
	} else {
		jsonObject.put("success", false);
		jsonObject.put("orderId", null);
		jsonObject.put("msg", "生成订单失败");
	}
	
	//更新内存中的订单缓存数据
//	if(SystemManager.ordersReport!=null){
//		SystemManager.ordersReport.setNotPayCount(SystemManager.ordersReport.getNotPayCount()+1);//订单++
////		SystemManager.ordersReport.getNotPayCount().incrementAndGet();//订单++
//	}
	return jsonObject;
	}
	
	

	@Override
	public Services<Order> getService() {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	
	
	/**
	 * 点击我的订单页面的未付款的订单进行付款操作,则跳转到付款页面进行付款
	 * @return
	 */
	 @RequestMapping(value = "/toPay", method = { RequestMethod.GET, RequestMethod.POST })
	 @ResponseBody
	 public Object toPay1(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
//		if (getLoginAccount() == null) {
//			return page_toLogin;
//		}
	    Map jsonObject = new HashMap<>();
		String orderid = RequestHolder.getRequest().getParameter("id");
		logger.error("orderid="+orderid);
		if(StringUtils.isBlank(orderid)){
			//throw new NullPointerException();
			jsonObject.put("success", false);
			jsonObject.put("orderId", null);
			jsonObject.put("msg", "根据订单号查询不到订单信息！");
			return jsonObject;
		}
		
		Order order = orderService.selectById(orderid);
		if(order==null){
			//throw new NullPointerException("根据订单号查询不到订单信息！");
			jsonObject.put("success", false);
			jsonObject.put("orderId", null);
			jsonObject.put("msg", "根据订单号查询不到订单信息！");
			return jsonObject;
		}
		
		Ordership ordership = ordershipService.selectOne(new Ordership(orderid));
		if(ordership==null){
			//throw new NullPointerException("根据订单号查询不到配送信息！");
			jsonObject.put("success", false);
			jsonObject.put("orderId", null);
			jsonObject.put("msg", "根据订单号查询不到配送信息！");
			return jsonObject;
		}
		
		//创建支付记录对象
		Orderpay orderpay = new Orderpay();
		orderpay.setOrderid(orderid);
		orderpay.setPaystatus(Orderpay.orderpay_paystatus_n);
		
		orderpay.setPayamount(Double.valueOf(order.getAmount()));
		orderpay.setPaymethod(Orderpay.orderpay_paymethod_alipayescow);
		int orderpayID = orderpayService.insert(orderpay);
		logger.debug("orderpayID="+orderpayID);
		
		order.setOrderpayID(String.valueOf(orderpayID));
		
		//查询配送地址信息
//		return "redirect:/phone/paygate/pay?orderId="+order.getId() + "&orderPayId="+orderpayID;
		jsonObject.put("success", true);
		jsonObject.put("orderId", orderid);
		jsonObject.put("msg", "");
		return jsonObject;
	}
	/**
	 * 换货申请 页面请求
	 * @author dzh
	 * @param String orderID订单ID
	 * @return 返回 申请页面
	 * 
	 * **/
	 @RequestMapping(value = "/changeProduct/show", method = { RequestMethod.GET, RequestMethod.POST })
	    public String changeProduct(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
		 String orderId = request.getParameter("orderId");
		 Account acc = new Account();
	     String token = request.getParameter("token");
	     acc = singleLoginUtil.singleLogin(token);
//	     if(!StringUtils.isBlank(token)){
//	    	 OrganMemberEntityAO om = SchUserUtil.getOrganMemberEntityAO(token);
//	        	if(null != om && StringUtils.isNotBlank(om.getId()) ){
//	        		String baseUserId = om.getId();
//	            	Account e = new Account();
//	            	e.setBaseuserid(baseUserId);
//	            	acc = accountService.selectOne(e);
//	        	}
//	     }else{
//	    	 Account e = new Account();
//         	e.setBaseuserid("3");
//         	acc = accountService.selectOne(e);
//	     }
	     
		 //根据订单ID获取 退货信息
		 ReturnProductInfoAO ao = new ReturnProductInfoAO();
		 ao = orderService.getReturnInfo(orderId, acc.getAccount());
		 if(ao.getStatus() ==null){
			 ao.setStatus(0);
			 ao.setFlag("0");
		 }
		 model.addAttribute("orderId", orderId);
		 model.addAttribute("ao", ao);
		 //根据订单ID获取 换货商品图片
		 FileInfoCriteria fileCr = new FileInfoCriteria();
		 fileCr.createCriteria().andFormIdEqualTo("ch"+orderId);
		 //fileCr.createCriteria().andFileIdLike("%34,047%");
		 List<FileInfoAO> fileList = new ArrayList<FileInfoAO>();
		 List<FileInfoAO> rs = fileInfoGeneratedMapper.selectByCriteria(fileCr);
		 if(rs != null && rs.size() >0){
			 fileList = rs;
		 }
		 model.addAttribute("fileList", fileList);
		 return "phone/order/changeProduct";
	 }
	 /**
		 * 换货信息保存
		 * @return
		 * @throws Exception 
		 */
		@RequestMapping(value = "/changeProduct/saveOrUpdate", method = RequestMethod.POST)
		@ResponseBody
		public String saveOrUpdate(Model model,HttpServletRequest request) throws Exception{
			int resInt = 0;
			String orderidStr = request.getParameter("orderId");
			String id = request.getParameter("id");
			String imgurl = request.getParameter("imgUrl");
			String token = request.getParameter("token");
			String backreson = request.getParameter("backreson");
			String statusStr = request.getParameter("status");
			int status = Integer.valueOf(statusStr);
			Order orderInfo = new Order();
			ReturnProductInfoAO returnProductInfoAO = new ReturnProductInfoAO();
			Account acc = new Account();
			if(!StringUtils.isBlank(token)){
				OrganMemberEntityAO om = SchUserUtil.getOrganMemberEntityAO(token);
	        	if(null != om && StringUtils.isNotBlank(om.getId()) ){
	        		String baseUserId = om.getId();
	            	Account e = new Account();
	            	e.setBaseuserid(baseUserId);
	            	acc = accountService.selectOne(e);
	        	}
	        }else{
	        	Account e = new Account();
            	e.setBaseuserid("3");
            	acc = accountService.selectOne(e);
	        }
			if(StringUtils.isNotBlank(id)){
				returnProductInfoAO = orderService.getReturnInfoById(id);
			}
			returnProductInfoAO.setImgurl(imgurl);
			returnProductInfoAO.setBackreson(backreson);
			returnProductInfoAO.setOrderid(orderidStr);
			returnProductInfoAO.setCreatedate(new Date());
			returnProductInfoAO.setStatus(status);
			returnProductInfoAO.setFlag("1");//等待卖家审核换货
			
	        if(acc != null && StringUtils.isNotBlank(acc.getId())){
	        	returnProductInfoAO.setCreatecode(acc.getAccount());
	        	if(com.alibaba.dubbo.common.utils.StringUtils.isBlank(id)){
	        		resInt = orderService.insertReturnInfo(returnProductInfoAO);
	        		//换货申请 提交成功 变更订单状态 为申请换货 待审批
	        		orderInfo = orderService.selectById(orderidStr);
	        		orderInfo.setRefundStatus("1");
	        		orderInfo.setChangePFlag("1");
	        		if(orderInfo != null && !StringUtils.isBlank(orderInfo.getId())){
	        			orderService.update(orderInfo);
	        		}
	        	}else{
	        		resInt = orderService.updateReturnInfo(returnProductInfoAO);
	        	}
	        }
			if(0 == resInt){
				return "false";
			}else{
				return "true";
			}
			
		}
		
	 public boolean checkLogin(HttpServletRequest request){
	    	boolean res = false;
	    	Account acc = new Account();
	        String token = request.getParameter("token");
	        if(StringUtils.isBlank(token)){
	        	return res;
	        }else{
	        	OrganMemberEntityAO om = SchUserUtil.getOrganMemberEntityAO(token);
	        	if(null != om && StringUtils.isNotBlank(om.getId()) ){
	        		String baseUserId = om.getId();
	            	Account e = new Account();
	            	e.setBaseuserid(baseUserId);
	            	acc = accountService.selectOne(e);
	        	}
	        }
	        if(acc != null && StringUtils.isNotBlank(acc.getId())){
	        	res = true;
	        }
	        return  res;
	    }
/***
 * 换货时  图片上传 保存图片路径到本地数据库
 * @param fileID 订单id
 * @param data 调用原生上传 图片后返回上传图片信息
 * **/
	 @RequestMapping(value = "/saveUploadImagPath", method = { RequestMethod.GET, RequestMethod.POST })
	    @ResponseBody
	    public Object saveUploadImagPath(HttpServletRequest request){
		 String id = request.getParameter("id");
		 String fileId = request.getParameter("fileId");
		 String fileName = request.getParameter("fileName");
		 String fileSize = request.getParameter("fileSize");
		 String fileExt = request.getParameter("fileExt");
		 boolean saveFlag = false;
		 FileInfoAO fileInfo = new FileInfoAO();
		 fileInfo.setCreateAt(new Date());
		 if(!StringUtils.isBlank(id)){
			 fileInfo.setFormId("ch"+id);
			 fileInfo.setFileId(fileId);
			 fileInfo.setFileName(fileName);
			 fileInfo.setFileSize(fileSize);
			 fileInfo.setFileExt(fileExt);
			 fileInfoGeneratedMapper.insert(fileInfo);
			 saveFlag = true;
		 }
		 return saveFlag;
	 }
	 
	 /***
	  * 换货时  移除本地库 图片保存信息
	  * @param ID 文件id
	  * @param 
	  * **/
	 	@RequestMapping(value = "/removeImgLocal", method = { RequestMethod.GET, RequestMethod.POST })
	 	    @ResponseBody
	 	    public Object removeImgLocal(HttpServletRequest request){
	 		 String fileID = request.getParameter("fileId");
	 		 if(!StringUtils.isBlank(fileID)){
	 			fileInfoGeneratedMapper.deleteByPrimaryKey(fileID);
	 		 }
	 		 return true;
	 	 }
	 	
	/**
	 * 支付时 获取银行流水号
	 * @throws IOException 
	 * 
	 * */
	@RequestMapping(value = "/getBankLsNo", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object getBankLsNo(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException{
		Object res = "201608191434481371378";
		String fee = "0";
		Account acc = new Account();
	    String token = request.getParameter("token");
	    String orderId = request.getParameter("orderId");
	    String browseType = "app";
	    String onLineStyle = "unionpay";
	    String retUrl = "";

	    /*Keyvalue key = new Keyvalue();
	    key.setId("53");
	    key = keyvalueService.selectOne(key);
	    if(key != null && StringUtils.isNotBlank(key.getValue())){
	    	centerUrl = key.getValue();
	    }*/
	    
	    
		OrganMemberEntityAO  om = SchUserUtil.getOrganMemberEntityAO(token);
		if (null == om) {
			Map jsonObject = new HashMap<>();
			jsonObject.put("success", false);
			jsonObject.put("orderId", null);
			jsonObject.put("msg", "您未登录，请登录后重试！");
			logger.info("您未登录，请登录后重试！");
			return jsonObject;
		}
	    
       Order order = new Order();
	   acc = singleLoginUtil.singleLogin(token);
	   if(!StringUtils.isBlank(orderId)){
		   order = orderService.selectById(orderId);
	   }
	   if(order != null && !StringUtils.isBlank(order.getId())){
		   fee = order.getAmount();
	   }
	   
	   
	   
		if (null != om) {
			//校园商城调用订单中心系统
		    //调用订单中心接口生成订单
		   String centerUrl = "http://sch.expopay.cn";
		   String url =  centerUrl +"/center/phone/order?token="+token;
		   
			Map<String, String> params = new HashMap<String, String>();
			params.put("type", "8");
			params.put("no", order.getId());
			params.put("memberCode", om.getCode());
			params.put("payAmount", order.getAmount());
			String responseHttp = HttpUtil.postJson(JSON.toJSONString(params), url,"UTF-8");
			logger.error("response = "+response);
			if(responseHttp != ""){
				JSON json =JSON.parseObject(responseHttp);
				Map<String,Map<String,String>> map = JSON.toJavaObject(json, Map.class);
				order.setOtherRequirement(map.get("data").get("id"));
				orderService.update(order);
				logger.error("map = "+map.get("data"));
				res = map.get("data");
			}
		}
	    return  res;
}
	
	/**
	 * 我的订单页 下拉加载数据
	 * 
	 * 
	 * */
	@RequestMapping(value = "/initGetOrderList", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object initGetOrderList(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
		 PagerModel pager = new PagerModel();
		//获取订单信息之前先执行单点登录
	        Account acc = new Account();
	        String token = request.getParameter("token");
	        acc = singleLoginUtil.singleLogin(token);
	        if(acc != null && StringUtils.isNotBlank(acc.getId())){
	        	
	        	 try {
					pager = getMyOrders(acc.getAccount());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    		//查询汇总
	    		LOG.error("获取订单信息成功！");
	        }
		return pager;
	}
	
	/***
	 * 买家确认退货 已经发货
	 * @f  
	 * **/
	@RequestMapping(value = "/updateReturnProductInfo", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object updateReturnProductInfo(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
		 String id = request.getParameter("id");
		 String orderId = request.getParameter("orderId");
		 String res = "false";
		 int i = 0;
		 String sallerAddress = request.getParameter("sallerAddress");
		 String pressName = request.getParameter("pressName");
		 String pressCode = request.getParameter("pressCode");
		 String pressNo = request.getParameter("pressNo");
		 
		 ReturnProductInfoAO retuenProductAO = new ReturnProductInfoAO();
		 Order order = new Order();
		 if(!StringUtils.isBlank(id)){
			 retuenProductAO = orderService.getReturnInfoById(id);
			 retuenProductAO.setBacksallerpresscode(pressCode);
			 retuenProductAO.setBacksallerpressname(pressName);
			 retuenProductAO.setSalleraddress(sallerAddress);
			 retuenProductAO.setBacksallerpressno(pressNo);
			 retuenProductAO.setFlag("3");
			 i = orderService.updateReturnInfo(retuenProductAO);
		 }
		 if(!StringUtils.isBlank(orderId)){
			 //order.setId(orderId);
			 order =  orderService.selectById(orderId);
			 order.setRefundStatus("3");
			i = orderService.update(order);
		 }
		 if(0 != i){
			res = "true"; 
		 }
		return res;
	}
	
	 /**
	  * 更新换货状态
	  * 
	  * **/
	@RequestMapping(value = "/updateReturnProductStatus", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object updateReturnProductStatus(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
		String res = "";
		 String id = request.getParameter("id");
		 String orderId = request.getParameter("orderId");
		 String returnStatusStr = request.getParameter("flag");
		 int i = 0;
		 ReturnProductInfoAO retuenProductAO = new ReturnProductInfoAO();
		 Order order = new Order();
		 if(!StringUtils.isBlank(id)){
			 retuenProductAO = orderService.getReturnInfoById(id);
			 if(!StringUtils.isBlank(returnStatusStr)){
				 retuenProductAO.setFlag(returnStatusStr); 
				 i = orderService.updateReturnInfo(retuenProductAO);
			 }
		 }
		 if(!StringUtils.isBlank(orderId)){
			 order =  orderService.selectById(orderId);
			 if(!StringUtils.isBlank(returnStatusStr)){
				 order.setRefundStatus(returnStatusStr);
				 order.setStatus("sign");
				 i =  orderService.update(order);
			 }
		 }
		 if(0 != i){
				res = "true"; 
			 }
		return res;
	}
}
